package org.zgjy.test;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.zgjy.DeviceConfig;
import org.zgjy.MqttTimerTask;
import org.zgjy.mapper.ModelMapper;
import org.zgjy.model.Device;
import org.zgjy.ModbusTimerTask;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


//@SpringBootApplication
//@MapperScan(basePackages = {"org"})
public class Main {

    public static void main(String[] args) throws Exception {

        List<Device> devices;
        ModbusTimerTask.configs = new ArrayList<>();

        String resource = "mybatis_conf.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        try(SqlSession session = sqlSessionFactory.openSession()){
            ModelMapper mapper = session.getMapper(ModelMapper.class);
            devices = mapper.selectDevice();
        }

        String filename = "src/main/resources/config/CL_FA201B.json";
        Path path = Paths.get(filename);
        String content;
        content = Files.readString(path);
        DeviceConfig config = JSON.parseObject(content, DeviceConfig.class);

        // 添加配置
        ModbusTimerTask.configs.add(config);
        ModbusTimerTask modbusTimerTask = new ModbusTimerTask("Task1", devices);

        Timer timer1 = new Timer();
        timer1.schedule(modbusTimerTask, 3L, 3000L);

        // 给 MqttService 装配消息源
        MqttTimerTask.add_message_source(modbusTimerTask);
        MqttTimerTask mqttTimerTask = new MqttTimerTask();

        Timer timer2 = new Timer();
        timer2.schedule(mqttTimerTask, 3L, 5000L);

        String strTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
        System.out.println("主线程:" + Thread.currentThread().getId() + " Time:" + strTime);

        //SpringApplication.run(Main.class, args);
    }
}
